/*
-----------------------------------------------------------------------------
This source file is part of the OGRE Reference Application, a layer built
on top of OGRE(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreRefAppBall.h"
#include "OgreRefAppWorld.h"
#include "OgreRefAppConstants.h"
#include "OgreRefAppUtils.h"
#include "OgreRefAppSteeringBehaviors.h"


#define __DEBUGON__


namespace OgreRefApp
{

    //-------------------------------------------------------------------------
    Ball::Ball(const String& name, Real radius) : ApplicationObject(name)
    {
        mRadius = radius;
        m_pOwner = NULL;
        setUp(name);

    }
    //-------------------------------------------------------------------------
    Ball::~Ball()
    {

    }

    Real Ball::getRadius(void)
    {
        return mRadius;
    }

    bool Ball::handleMessage(const ApplicationObject::CollisionInfo& msg)
    {



        return true;
    }
    //-------------------------------------------------------------------------
    void Ball::setUp(const String& name)
    {
        // Create visual presence
        SceneManager* sm = World::getSingleton().getSceneManager();
        mEntity = sm->createEntity(name, "sphere.mesh");
        mSceneNode = sm->getRootSceneNode()->createChildSceneNode(name);
        // Scale down, default size is 100
        Real scale = mRadius / 100.0f;
        mSceneNode->scale(scale, scale, scale);
        maxLinearVelocity=100;
        maxAngularVelocity=100;
        maxForce=100;


        mSceneNode->attachObject(mEntity);
        // Add reverse reference
        mEntity->setUserObject(this);

        // Create mass body
        mOdeBody = new dBody(World::getSingleton().getOdeWorld()->id());
        // Set reverse reference
        mOdeBody->setData(this);
        // Set mass
        setMassSphere(0.1, mRadius); // TODO change to more realistic values

        this->setBounceParameters(0.7, 0.1);
        this->setSoftness(0.0f);

        this->setFriction(Math::POS_INFINITY);

        this->setLinearDamping(0.0005);

        this->setAngularDamping(0.02);

        // Create collision proxy
        dSphere* odeSphere = new dSphere(0, mRadius);
        mCollisionProxies.push_back(odeSphere);
        updateCollisionProxies();

    }

    void Ball::_notifyCollided(ApplicationObject* otherObj, const ApplicationObject::CollisionInfo& info)
    {
        //otherObj->handleMessage(info);


    }

    void Ball::update(void)
    {

    }

    Ogre::Vector3 Ball::AddNoiseToKick(Ogre::Vector3 BallPos, Ogre::Vector3* BallTarget)
    {



        Real displacement = (Pi - Pi*PlayerKickingAccuracy) * RandomClamped();
        //Ogre::Vector3 toTarget = ( Ogre::Vector3( BallTarget->x, BallTarget->y, BallTarget->z) )/( Ogre::Vector3( BallTarget->x, BallTarget->y, BallTarget->z) ).normalise();
        Ogre::Vector3 toTarget = ( Ogre::Vector3( BallTarget->x, BallTarget->y + BallTarget->y*displacement, BallTarget->z) );

        //Ogre::Vector3 toTarget = ( Ogre::Vector3( BallTarget->x, BallTarget->y, BallTarget->z) - BallPos )/( Ogre::Vector3( BallTarget->x, BallTarget->y, BallTarget->z) - BallPos ).normalise();
        //Ogre::Vector3 toTarget = Ogre::Vector3( BallTarget->x, BallTarget->y, BallTarget->z );

        //toTarget = toTarget.randomDeviant( Ogre::Radian( displacement/100000 ));

        return toTarget;

    }



    //-------------------------- Kick ----------------------------------------
    //
    //  applys a force to the ball in the direction of heading. Truncates
    //  the new velocity to make sure it doesn't exceed the max allowable.
    //------------------------------------------------------------------------
    void Ball::Kick(Ogre::Vector3 direction, Real force)
    {

        //calculate the acceleration
        Ogre::Vector3 velocity = (( direction - getPosition() ) / ( direction - getPosition() ).normalise() ) * force;

        //update the velocity
        this->setLinearVelocity(velocity);
    }


//---------------------- TimeToCoverDistance -----------------------------
//
//  Given a force and a distance to cover given by two vectors, this
//  method calculates how long it will take the ball to travel between
//  the two points
//------------------------------------------------------------------------
    Real Ball::TimeToCoverDistance(Ogre::Vector3 from,
                                           Ogre::Vector3 to,
                                           Real force)
    {
        //this will be the velocity of the ball in the next time step *if*
        //the player was to make the pass.
        //Real speed = force / m_dMass;

        Real speed = force;

        //calculate the velocity at B using the equation
        //
        //  v^2 = u^2 + 2as
        //

        //first calculate s (the distance between the two positions)
        Real DistanceToCover =  from.distance( to );

        Real term = speed*speed + 2.0*DistanceToCover*getLinearDamping();

        //if  (u^2 + 2as) is negative it means the ball cannot reach point B.
        if (term <= 0.0) return -1.0;

        Real v = sqrt(term);

        //it IS possible for the ball to reach B and we know its speed when it
        //gets there, so now it's easy to calculate the time using the equation
        //
        //    t = v-u
        //        ---
        //         a
        //
        return (v-speed)/getLinearDamping();
    }





}
